package cn.fayang.ymcc.mq.consumer;

import cn.fayang.ymcc.constant.util.AssertUtil;
import cn.fayang.ymcc.domain.PayOrder;
import cn.fayang.ymcc.dto.PayDto;
import cn.fayang.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 消费者,将order发送的订单消息储存
 */
@Component
@RocketMQMessageListener(
        consumerGroup="course-order-pay-consumer",
        topic="course-order-topic",
        selectorExpression="course-order-tag"
)
public class SavaPayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;
    /**
     * 消费消息 保存支付订单
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        //从mq消息体中拿值
        byte[] body = messageExt.getBody();
        //判断消息体是否有值
        AssertUtil.isNotNull(body,"消息体为空");
        // 将消息体中的byte数组转化为对象
        String jsonStr = new String (body, StandardCharsets.UTF_8);
        PayDto dto = JSONObject.parseObject(jsonStr, PayDto.class);
        //判断支付单是否存在,如果 存在直接接收消息  不报错即为签收消息
        PayOrder payOrder = payOrderService.selecByOrderNO(dto.getOrderNo());
        if(payOrder != null){
            return;
        }
        //将消息体中的dto拷贝为支付单
       payOrder = new PayOrder();
        BeanUtils.copyProperties(dto,payOrder);
        payOrder.setCreateTime(new Date());
        //将支付单对象设置为未支付
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        //保存支付单
        payOrderService.insert(payOrder);
    }
}
